<!--  -->
<template>
    <div style="margin-top: -35px;">
        <!-- 表头 -->
        <div class="flex aic jcfe">
            <ElButton type="primary" clearable :icon="Plus" @click="onAdd" style="margin-right: 16px;">新增模块</ElButton>
            <el-select v-model="state.ruleForm.region" placeholder="请选择复制报名表模板">
                <el-option @click="copy(item)" :label="item.templateName" :value="item.templateValue"
                    v-for="(item, index) in state.options" :key="index" />
            </el-select>
        </div>
        <!-- 表体 -->
        <div class="" v-if="state.templateValue.length != 0">
            <div class="" v-for="(item, index) in state.templateValue" :key="index">
                <h4 class="fonts24 fontw500 flex jcsb">
                    {{ item.name }}
                    <div style="margin-top: -5px;">
                        <ElButton type="" :icon="Plus" @click="onAddText(index)" style="margin-right: 16px;">新增字段
                        </ElButton>
                        <ElButton type="" :icon="Edit" @click="editText(item)" style="margin-right: 16px;">修改模块
                        </ElButton>
                        <ElButton type="danger" @click="deteleMokuia(item.id)" style="margin-right: 16px;">删除模块
                        </ElButton>
                    </div>

                </h4>
                <div class="fromTable_main">
                    <div class="" v-for="(items, indexs) in item.setData" :key="indexs">
                        <p class="flex aic " v-if="items.editBool">
                            <span class="" style="color: red;" v-if="items.rulesBool">*</span>
                            <span style="margin: 0 8px;">{{ items.label }}</span>
                            <el-icon :size="16" @click="edit(items)">
                                <Edit />
                            </el-icon>
                        </p>
                        <el-input style="width: 240px;margin: 10px 0px;" @blur="editInput(items)" v-if="!items.editBool"
                            v-model="items.label" placeholder="请输入字段名称" />
                        <div class="flex aic">
                            <div>
                                <el-input v-if="items.type == 'text'" style="width: 240px;" :disabled="true"
                                    :placeholder="`请输入${items.label}`" />
                                <el-select v-if="items.type == 'select'" style="width: 240px;" class="m-2"
                                    :placeholder="`请选择${items.label}`">
                                    <el-option v-for="item in dictFun(items.dictValue)" :key="item.dictValue"
                                        :label="item.dictLabel" :value="item.dictValue" />
                                </el-select>
                                <div class="uploadImages" v-if="items.type == 'uploadImage'||items.type == 'uploadImages'">
                                    <el-icon class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </div>
                                <el-date-picker v-if="items.type == 'date-picker'" style="width: 240px;" type="date"
                                    placeholder="请选择日期" />
                                <el-date-picker v-if="items.type == 'dateTime-picker'" style="width: 240px;" type="datetime"
                                    placeholder="请选择日期时间" />
                                <el-input v-if="items.type == 'textarea'" :placeholder="`请输入${items.label}`" :rows="2"
                                    type="textarea" style="width: 240px;"/>
                            </div>

                            <span style="margin: 0px 16px;">非必填</span>
                            <el-switch v-model="items.rulesBool" class="ml-2" />
                            <span style="margin: 0px 16px;">必填</span>
                            <el-button type="danger" :icon="Delete" @click="deteleText(index, items)">删除</el-button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <div class="width100" v-else>
            <el-empty description="暂无数据" />
        </div>
    </div>
    <!-- 新增模块 -->
    <Dialog v-model="dialogVisible1" :title="state.dialogVisible1Title" width="520">
        <el-form ref="ruleFormRefs" :model="state.textForm" :rules="rules" label-width="160px" class="demo-ruleForm"
            status-icon>
            <el-form-item label="报名表模块名称：" prop="name">
                <el-input v-model="state.textForm.name" placeholder="请输入报名表模块名称" />
            </el-form-item>
            <el-form-item label="报名表模块排序：" prop="number" style="margin-top: 16px;">
                <el-input-number v-model="state.textForm.number" placeholder="请输入报名表模块排序" />
            </el-form-item>
            <el-form-item style="margin-top: 16px;" class="flex jcc">
                <el-button type="primary" @click="submitForm(ruleFormRefs)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRefs)">取消</el-button>
            </el-form-item>
        </el-form>
    </Dialog>
    <!-- 新增字段 -->
    <Dialog v-model="dialogVisible2" :title="state.dialogVisible2Title" width="520">
        <el-form ref="ruleFormRef2" :model="state.textForm2" :rules="rules" label-width="160px" class="demo-ruleForm"
            status-icon>
            <el-form-item label="字段名称：" prop="label">
                <el-input v-model="state.textForm2.label" placeholder="请输入字段名称" />
            </el-form-item>
            <el-form-item label="输入类型：" prop="type" style="margin-top: 16px;">
                <el-select v-model="state.textForm2.type" class="m-2" placeholder="请选择字段类型">
                    <el-option v-for="item in state.optionsType" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="绑定字典：" v-if="state.textForm2.type == 'select'" prop="dictValue" style="margin-top: 16px;">
                <el-select v-model="state.textForm2.dictValue" class="m-2" placeholder="请选择绑定字典">
                    <el-option v-for="item in state.dictData" :key="item.dictType" :label="item.dictName"
                        :value="item.dictType" />
                </el-select>
            </el-form-item>
            <el-form-item style="margin-top: 16px;" class="flex jcc">
                <el-button type="primary" @click="submitForm2(ruleFormRef2)">
                    保存
                </el-button>
                <el-button @click="resetForm2(ruleFormRef2)">取消</el-button>
            </el-form-item>
        </el-form>
    </Dialog>
</template>

<script lang="ts" setup>
import { formTemplateList } from "@/api/resume/index"
import { dictSect } from "@/utils/dictUnit"
import type { FormInstance, FormRules } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, unref, watch } from "vue"
const emit = defineEmits(['FromTableClick'])
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const props = defineProps({
    data: {
        type: Array,
        default: () => []
    }
})
const state = reactive({
    dictData: [] as any,
    ruleForm: {} as any,
    textForm: {} as any,
    textForm2: {} as any,
    react: false,
    options: [] as any,
    optionsType: [
        { label: "文本框", value: "text" },
        { label: "选择框", value: "select" },
        { label: "选择日期", value: "date-picker" },
        // { label: "dateTime-picker", value: "dateTime-picker" },
        { label: "多行文本框", value: "textarea" },
        { label: "上传单个图片", value: "uploadImage" },
        { label: "上传多个图片", value: "uploadImages" },
    ],
    templateValue: [
        {
            id: "0",
            name: "个人信息",
            number: 0,
            setData: [
                {
                    id: "01",
                    editBool: true,//判断修改按钮
                    label: "姓名",//名称
                    type: "text",//类型
                    rulesBool: false,//必填、非必填
                    dictValue: 'sys_dict'
                }
            ]
        }
    ] as any,
    dialogVisible1Title: "新增报名表模块",
    dialogVisible2Title: "新增模块字段",
    textValue: "",
})
watch(() => props.data, (newValue: any) => {
    state.templateValue = newValue
}, { deep: true, immediate: true })
watch(() => state.templateValue, (newValue: any) => {
    emit("FromTableClick", newValue)
}, { deep: true })
const ruleFormRefs = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
interface RuleForm {
    name: string
    number: number
    label: string
    dictValue: string,
    type: string
}
const dictFun = (item) => {
    return dictSect(item)
}
const rules = reactive<FormRules<RuleForm>>({
    label: [
        { required: true, message: '请输入字段名称', trigger: 'blur' },
        { min: 1, max: 50, message: '请输入1~50字', trigger: 'blur' },
    ],
    dictValue: [
        { required: true, message: '请输入绑定字典名称', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入报名表模块名称', trigger: 'blur' },
        { min: 1, max: 50, message: '请输入1~50字', trigger: 'blur' },
    ],
    number: [
        { required: true, message: '请输入报名表模块序号', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请选择绑定字典类型', trigger: 'blur' }
    ]
})

const onAdd = () => {
    console.log("新增");
    state.dialogVisible1Title = "新增报名表模块"
    state.textForm = {}
    state.textForm.number = state.templateValue.length
    dialogVisible1.value = true
}
const editText = (items) => {
    state.dialogVisible1Title = "编辑报名表模块"
    state.textForm = items
    dialogVisible1.value = true
}
const onAddText = (index) => {
    state.textForm2 = {}
    state.textValue = index
    dialogVisible2.value = true
    console.log("新增");
}
function deleteFun(id, data) {
    let index = data.findIndex(obj => obj.id === id);
    if (index !== -1) {
        data.splice(index, 1);
    }
    return data
}
const deteleMokuia = (id) => {
    console.log("删除");
    ElMessageBox.confirm('确认删除该报名表模块？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        state.templateValue = deleteFun(id, state.templateValue)
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })
}
const edit = (items) => {
    items.editBool = !items.editBool
}
const editInput = (items) => {
    if (items.label == "") {
        ElMessage({
            type: 'error',
            message: `字段名称不可为空！`,
        })
    } else {
        items.editBool = true
    }
}
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            if (state.dialogVisible1Title == '新增报名表模块') {
                let obj = {
                    id: new Date().getTime(),
                    name: state.textForm.name,
                    number: state.textForm.number,
                    setData: []
                }
                state.templateValue.push(obj)
                state.templateValue = state.templateValue.sort((a, b) => a.number - b.number);
                dialogVisible1.value = false
            } else {
                state.templateValue = state.templateValue.sort((a, b) => a.number - b.number);
                dialogVisible1.value = false
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    if (!formEl) return
    formEl.resetFields()

}
const deteleText = (index, items) => {
    console.log("删除");
    ElMessageBox.confirm('确认删除该模块字段？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        state.templateValue[index].setData = deleteFun(items.id, state.templateValue[index].setData)
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })
}
// 新增模块字段---------------------------------------------------------------------------
const submitForm2 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            if (state.dialogVisible2Title == '新增模块字段') {
                let obj = {
                    id: new Date().getTime(),
                    editBool: true,//判断修改按钮
                    label: state.textForm2.label,//名称
                    type: state.textForm2.type,//类型
                    rulesBool: false,//必填、非必填
                    dictValue: state.textForm2.dictValue,
                    value:state.textForm2.type!="uploadImages"?"":[],//值
                }
                state.templateValue[state.textValue].setData.push(obj)
                console.log("新增字段", state.templateValue[state.textValue].setData);
                // state.templateValue = state.templateValue.sort((a, b) => a.number - b.number);
                dialogVisible2.value = false
            } else {
                // state.templateValue = state.templateValue.sort((a, b) => a.number - b.number);
                dialogVisible2.value = false
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm2 = (formEl: FormInstance | undefined) => {
    dialogVisible2.value = false
    if (!formEl) return
    formEl.resetFields()

}
const copy = (item) => {
    state.templateValue = JSON.parse(item.templateValue)
}
const formTemplateListApi = async () => {
    await formTemplateList({ pageNum: 1, pageSize: 10000 }).then((res: any) => {
        state.options = res.rows
    })
}
formTemplateListApi()
const info = async () => {
    state.dictData = JSON.parse(sessionStorage.getItem("dictData")) || []
}
info()
</script>

<style lang="less" scoped>
.uploadImages {
    width: 90px;
    height: 90px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.fromTable_main {
    display: grid;
    grid-template-columns: repeat(2, 50%);
}

.width100 {
    width: 100%;
}

h4 {

    position: relative;
    margin: 0;
    margin-bottom: 26px;
    margin-top: 20px;
    padding-left: 20px;

    &::after {
        position: absolute;
        left: 0px;
        top: 5px;
        content: "";
        width: 8px;
        height: 24px;
        background: #2F6CBC;
        border-radius: 0px 4px 4px 0px;
        opacity: 1;
    }

    border-bottom: 1px solid #d7d7d7;
}
</style>